<hr>
<p>title: 268.missing number<br>date: 2021-10-18 14:49:02<br>tags:</p>
<pre><code>- LeeCode
</code></pre><p>categories: </p>
<pre><code>- LeeCode
</code></pre><p>hidden: true</p>
<h2 id="cateHidden-false"><a href="#cateHidden-false" class="headerlink" title="cateHidden: false"></a>cateHidden: false</h2><h3 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h3><blockquote>
<p>Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.</p>
<p>查找给定范围内缺少的数字。</p>
</blockquote>
<h3 id="测试用例"><a href="#测试用例" class="headerlink" title="测试用例"></a>测试用例</h3><pre><code class="lang-bash">Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
</code></pre>
<h3 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h3><p>因为元素范围是[0,n]的连续数字，通过计算理想范围的“和”和实际数字的“和”进行对比。</p>
<pre><code class="lang-js">var missingNumber = function(nums) {
    if(nums.length === 1 &amp;&amp; nums[0] === 0) return 1;
    let min_num = -1, max_num = 0, sum = 0, range_sum = 0;
    // 计算当前数字的和，记录最小值和最大值
    for(let i = 0; i &lt; nums.length; i++) {
        if(nums[i] === 0) min_num = nums[i];
        else if(nums[i] &gt;= max_num) max_num = nums[i];
        sum += nums[i];
    }
    if(min_num === -1) return 0;
    // 计算理想数据范围的和
    range_sum = (1 + max_num) * max_num / 2;
    return range_sum - sum ? range_sum - sum : max_num + 1;
};
</code></pre>
<h3 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h3><blockquote>
<p>Accepted</p>
<p>122/122 cases passed (107 ms)</p>
<p>Your runtime beats 35.98 % of javascript submissions</p>
<p>Your memory usage beats 80.34 % of javascript submissions (40.9 MB)</p>
</blockquote>
